<template>
	<div v-waterMarker class="merak-float" v-loading="loading">
		<div class="header">
			<div class="leftTitle">
				<div class="icon" @click="emit('close',state.refresh)">
					<el-icon size="20">
						<ArrowLeft />
					</el-icon>
				</div>
				<div class="title">{{$t('goods_attribute.add_clearance')}}</div>
			</div>
			<div class="btnBox">
				<el-button type="primary" plain
					@click="submitForm(ruleFormRef,true)">{{ $t("merak.save_continue") }}</el-button>
				<el-button type="primary" @click="submitForm(ruleFormRef,false)">{{ $t("merak.save") }}</el-button>
			</div>
		</div>
		<div class="content">
			<div class="merak-float-overflow-y">
				<el-form ref="ruleFormRef" labelPosition="top" :model="ruleForm" :rules="rules">
					<div class="group">
						<div class="titleHeader" @click="state.basicsMsg = !state.basicsMsg">
							<el-icon size="16" v-if="state.basicsMsg">
								<CaretRight />
							</el-icon>
							<el-icon size="16" v-else>
								<CaretBottom />
							</el-icon>
							<div class="group-title">{{$t("goods_attribute.basic_information")}}</div>
						</div>
						<el-row :gutter="40" v-if="!state.basicsMsg">
							<el-col :span="6">
								<el-form-item :label="$t('goods_attribute.type_id')" prop="type_id">
									<el-select filterable class="qf_select" :placeholder="$t('merak.placeholder_select')" v-model="ruleForm.type_id">
										<el-option :label="item?.label" :value="item?.value"
											v-for="item in opstionsObjs?.goodsTypeArr" :key="item?.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_attribute.cc_property')" prop="cc_property" :error="newRules.cc_property">
									<el-input class="qf_input" type="text" v-model.trim="ruleForm.cc_property" />
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_attribute.cc_property_cn')" prop="cc_property_cn" :error="newRules.cc_property_cn">
									<el-input class="qf_input" type="text" v-model.trim="ruleForm.cc_property_cn" />
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_attribute.cc_property_en')" prop="cc_property_en" :error="newRules.cc_property_en">
									<el-input class="qf_input" type="text" v-model.trim="ruleForm.cc_property_en"/>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_attribute.cc_prop_type')" prop="cc_prop_type">
									<el-select class="qf_select" :placeholder="$t('merak.placeholder_select')" v-model="ruleForm.cc_prop_type" @change="showTable">
										<el-option :label="item?.label" :value="item?.value"
											v-for="item in opstionsObjs?.propType" :key="item?.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_attribute.cc_is_required')">
								<el-radio-group v-model="ruleForm.cc_is_required">
										<el-radio value="1">{{$t('merak.yes')}}</el-radio>
										<el-radio value="0">{{$t('merak.no')}}</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_attribute.is_spec')">
									<el-radio-group v-model="ruleForm.is_spec">
										<el-radio value="1">{{$t('merak.yes')}}</el-radio>
										<el-radio value="0">{{$t('merak.no')}}</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
						</el-row>
					</div>
					<div class="group" :class="state.propertyList?'':'group-table'" v-if="isShowTable">
						<div class="group-head">
							<div class="titleHeader" @click="state.propertyList = !state.propertyList">
								<el-icon size="16" v-if="state.propertyList">
									<CaretRight />
								</el-icon>
								<el-icon size="16" v-else>
									<CaretBottom />
								</el-icon>
								<div class="group-title">{{$t('goods_attribute.attribute_value_list')}}</div>
							</div>
							<div class="btnBox">
								<el-button type="primary" plain @click="addRows">{{$t('goods_attribute.add_enumeration_value')}}</el-button>
							</div>
						</div>
						<div class="float-table-row" v-if="!state.propertyList">
							<div class="table-box">
								<basicTableSum ref="editTableRef" v-bind="tableConfig" @editFormFun="editFormClick" >

									<template #handle="{ row }">

										<el-button type="danger" link @click="delFun(row)">{{$t('merak.delete')}}</el-button>

									</template>
								</basicTableSum>
							</div>
						</div>
					</div>
				</el-form>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
	import type { FormInstance, FormRules, } from "element-plus";
	import { getCurrentInstance, ref, reactive, computed, watch, onMounted } from "vue";
	import basicTableSum from "@/components/MerakEditTable/components/basicTable/moreEdit.vue";
	import { RouteType, editClearancGoodsProperty,addClearancGoodsProperty } from "@/api/modules/goodsArchive/allocation";
	import { failMsg,successMsg } from "@/utils/messageUtils";
	const { proxy } = getCurrentInstance()!;
	const props = defineProps<{
		type : RouteType;
		propId?:string|number;
		typeId?:string|number;
	}>();
	const ruleFormRef = ref<FormInstance>()
	const editTableRef = ref<FormInstance>()
	const loading = ref(true);
	const ruleForm = reactive({
		"type_id": "",//商品类型
		"cc_property": "",//属性名称(俄文)
		"cc_property_cn": "",//属性名称(中文)
		"cc_property_en": "",//属性名称(英文)
		"cc_prop_type": "",//属性类型
		"cc_is_required": "0",//是否必填
		"is_spec": "0",//是否是规格
	})
	//页面的select下拉数据
	const opstionsObjs = reactive({
		goodsTypeArr: [],//商品类型
		propType: [],//属性类型
		nounType: [],//名词性
		isQifa: [
			{
				label: proxy!.$t("merak.yes"),
				value: "1"
			},
			{
				label: proxy!.$t("merak.no"),
				value: "0"
			}
		]
		
	})
	const newRules = reactive<FormRules<RuleForm>>({})
	const validateInput = (rule, value, callback) => {
	  const regexPattern = /^[a-z][a-z0-9_]*$/; // 这里是一个简单的正则表达式，匹配字母和数字
	  if (!value || !regexPattern.test(value)) {
	    return callback(new Error(proxy!.$t("goods_attribute.input_error")));
	  }
	  callback();
	};
	const rules = reactive<FormRules<RuleForm>>({
		type_id: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'change',
			},
		],
		cc_property: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'blur',
			},
		],
		cc_property_cn: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'blur',
			},
		],
		cc_property_en: [
			{
				validator: validateInput, 
				trigger: 'blur' ,
			},
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'blur',
			},
		],
		cc_prop_type: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'change',
			},
		],
	})
	const emit = defineEmits<{
		close : [refresh: boolean];
	}>();

	const state = reactive<{
		refresh : boolean;
		basicsMsg : boolean;
		propertyList : boolean;

	}>({
		refresh: false,
		basicsMsg: false,
		propertyList: false,
	});

	const addRows = () => {
		editStatusType.value = "add";
		let obj = {
			cc_propvalue: {
				label: "",
				value: "",
			},
			cc_propvalue_cn: {
				label: "",
				value: ""
			},
			remark: {
				label: "",
				value: ""
			},
			remark_cn: {
				label: "",
				value: ""
			},
		};
		tableData.value.push(obj);
		nextTick(()=>{
			editTableRef.value.initBottomScroll()
		})
	}
	const tableHeadData = reactive([]);
	const tableData = ref([]);
	const headConfig = reactive({});//头部配置是否可编辑 
	const editStatusType = ref("");
	const tableConfig = reactive<{
		headData : [];
		tableData : [];
		headConfig : [];
	}>({
		headData: tableHeadData,//表格头部数据   必须值
		tableData: tableData,//表格内容数据      必须值
		headConfig: headConfig,//可编辑列类型    必须值 
	})

	//获取初始化数据
	const initMsg = () => {
		let data = {};
		if(props.propId != ""){
			data.prop_id = props.propId
		}
		editClearancGoodsProperty(props.type,data).then(({ code, data }) => {
			if (code == 2000) {
				opstionsObjs.goodsTypeArr = data.dataarr.type_id;//商品类型
				opstionsObjs.propType = data.dataarr.cc_prop_type;//属性类型
				if(props.propId != "" && props.propId != "all"){
					ruleForm.type_id = Number(props.typeId);
				}
				
				if(props.propId != "" && props.propId != undefined){
					
					ruleForm.cc_property = data.defaults.cc_property;
					ruleForm.cc_property_cn = data.defaults.cc_property_cn;
					ruleForm.cc_property_en = data.defaults.cc_property_en;
					ruleForm.cc_prop_type = data.defaults.cc_prop_type;
					ruleForm.cc_is_required = String(data.defaults.cc_is_required);
					ruleForm.is_spec = String(data.defaults.is_spec);
					
					let newArr = [];
					if(data.defaults.cc_prop_type == 'dropdown'){
						isShowTable.value = true
					}
					if(data.defaults.propvalueList){
						data.defaults.propvalueList.map(tableItem=>{
							newArr.push({
								cc_propvalue: {
									label: tableItem.cc_propvalue,
									value: tableItem.cc_propvalue,
								},
								cc_propvalue_cn: {
									label: tableItem.cc_propvalue,
									value: tableItem.cc_propvalue
								},
								remark: {
									label: tableItem.cc_propvalue,
									value: tableItem.cc_propvalue
								},
								remark_cn: {
									label: tableItem.cc_propvalue,
									value: tableItem.cc_propvalue
								},
							})
						})
						tableConfig.tableData = newArr;
					}
					setTimeout(()=>{
						loading.value = false;
					},0)
				} else {
					loading.value = false
				}
			}
		})
	}
	const isShowTable = ref(false);
	const showTable = (e) => {
		if(ruleForm.cc_prop_type == 'dropdown'){
			isShowTable.value = true;
		} else {
			isShowTable.value = false;
		}
		
	}
	const delFun = (e) => {
		tableConfig.tableData.splice(e.index, 1);
	}
	const editFormClick = (e) => {
		const idx = e.index;
		const editItem = {};
		Object.assign(editItem, e);
		delete editItem["index"];
		tableConfig.tableData[idx] = editItem;
	}


	const submitForm = async (formEl : FormInstance | undefined,isHide:boolean) => {
		
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				let tableDataArr = [];
				if(ruleForm.cc_prop_type == 'dropdown'){
					tableDataArr = editTableRef.value.submitData();
					if(tableDataArr != '' && tableDataArr.length > 0){
						for(let i = 0;i<tableDataArr.length;i++){
							let titem = tableDataArr[i];
							if(titem.cc_propvalue == "" || titem.cc_propvalue_cn == ""){
								failMsg(proxy!.$t("goods_attribute.add_error"))
								return false;
							}
						}
					} else {
						failMsg(proxy!.$t("goods_attribute.add_hint"))
						return false;
					}
					
				}
				
				let postData = {
					prop:ruleForm
				}
				if(ruleForm.cc_prop_type == "dropdown"){
					postData.propvalue = tableDataArr;
				}
				if(Object.keys(newRules).length > 0){
					Object.keys(newRules).map((key) => {
					  newRules[key] = undefined;
					});
				}
				addClearancGoodsProperty(props.type,postData).then(({ code, data,message }) => {
					if (code == 2000) {
						successMsg(proxy!.$t("goods_attribute.add_success"));
						formEl.resetFields()
						tableConfig.tableData = [];
						state.refresh = true;
						if(!isHide){
							emit('close',state.refresh)
						}
					} else {
						data.map(errorItem =>{
							newRules[errorItem] = message;
						})
					}
				})
			} else {
				console.log('error submit!', fields)
			}
		})
	}
	onMounted(() => {
		initMsg()
		let tableHead = [{
			title: proxy!.$t("goods_attribute.cc_propvalue"),
			field: 'cc_propvalue'

		}, {
			title: proxy!.$t("goods_attribute.cc_propvalue_cn"),
			field: 'cc_propvalue_cn'
		}, {
			title: proxy!.$t("goods_attribute.remark"),
			field: 'remark'
		},
		{
			title: proxy!.$t("goods_attribute.remark_cn"),
			field: 'remark_cn'

		},
		]
		Object.assign(tableHeadData, tableHead);
		let headCon = {
			cc_propvalue: "input",
			cc_propvalue_cn: "input",
			remark: 'input',
			remark_cn: 'input',
		}
		Object.assign(headConfig, headCon);

		let tableDataArr = [];
		tableData.value = tableDataArr;
	})
</script>

<style type="text/css">
	@import "./addCardTwo.scss";
</style>